import { Form, Button, Col, Input, Row, Select, message, Tabs } from 'antd';
import React, { useState, useEffect } from 'react';
import { Link, connect, history, FormattedMessage, formatMessage } from 'umi';
import styles from './style.less';
import PasswordValidInput from '@/components/PasswordValidInput';
const FormItem = Form.Item;
const { Option } = Select;
const { TabPane } = Tabs;
const InputGroup = Input.Group;

const Register = ({ dispatch }) => {
  const [count, setcount] = useState(0);
  const [prefix, setprefix] = useState('86');
  const [registerType, setRegisterType] = useState('email')
  const [captchaKey,setCaptchaKey] = useState();
  const [registing,setRegisting] = useState(false);

  let interval;
  const [form] = Form.useForm();
  useEffect(
    () => () => {
      clearInterval(interval);
    },
    [],
  );

  const onGetCaptcha = async () => {
    console.log(form)
    if (registerType === 'email') {
      await form.validateFields(['email'])
      dispatch({
        type: 'common/sendMailCaptcha',
        payload:{
          email:form.getFieldValue("email")
        }
      }).then((data) => {
        setCaptchaKey(data)
        countDown()
      })
    }

  };

  const countDown = () => {
    let counts = 59;
    setcount(counts);
    interval = window.setInterval(() => {
      counts -= 1;
      setcount(counts);
      if (counts === 0) {
        clearInterval(interval);
      }
    }, 1000);
  }
  const onFinish = (values) => {
    if (registerType === 'email') {
      setRegisting(true)
      dispatch({
        type: 'user/registerEmail',
        payload: { 
          ...values,
          captchaKey:captchaKey
        },
      }).then((success) => {
        setRegisting(false)
        if(success) {
          history.push({
            pathname: '/user/register-result',
            state: {
              ...values
            },
          });
        }
      });
    }
  };

  const checkConfirm = (_, value) => {
    const promise = Promise;

    if (value && value !== form.getFieldValue('password')) {
      return promise.reject(
        '两次输入的密码不匹配',
      );
    }

    return promise.resolve();
  };

  const changePrefix = (value) => {
    setprefix(value);
  };

  const renderRegisterContent =
    (
      <Form form={form} name="UserRegister" onFinish={onFinish}>
        <FormItem

          name="username"
          rules={[
            {
              required: true,
              message: formatMessage({
                id: '请输入用户名',
              }),
            },
            {
              pattern: /^[0-9a-zA-Z.!@&?]{5,30}$/,
              message: '用户名格式错误',
            },
          ]}
        >
          <Input
            placeholder='用户名'
          />
        </FormItem>
        { registerType === 'phone' && (<InputGroup compact>
          <Select
            size="large"
            value={prefix}
            onChange={changePrefix}
            style={{
              width: '20%',
            }}
          >
            <Option value="86">+86</Option>
            {/* <Option value="87">+87</Option> */}
          </Select>
          <FormItem
            style={{
              width: '80%',
            }}
            name="mobile"
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
              {
                pattern: /^\d{11}$/,
                message: '手机号格式错误',
              },
            ]}
          >
            <Input
              placeholder='请输入手机号'
            />
          </FormItem>
        </InputGroup>)}
        {registerType === 'email' && (<FormItem
          name="email"
          rules={[
            {
              required: true,
              message: '请输入邮箱',
            },
            {
              type: 'email',
              message: '请输入正确的邮箱',
            },
          ]}
        >
          <Input
            placeholder={formatMessage({
              id: '请输入邮箱',
            })}
          />
        </FormItem>)}
        <PasswordValidInput form={form}></PasswordValidInput>
        <FormItem
          name="confirm"
          rules={[
            {
              required: true,
              message: "确认密码",
            },
            {
              validator: checkConfirm,
            },
          ]}
        >
          <Input
            size="large"
            type="password"
            placeholder='请确认密码'
          />
        </FormItem>

        <Row gutter={8}>
          <Col span={16}>
            <FormItem
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码',
                },
              ]}
            >
              <Input
                size="large"
                placeholder='请输入验证码'
              />
            </FormItem>
          </Col>
          <Col span={8}>
            <Button
              disabled={!!count}
              className={styles.getCaptcha}
              onClick={onGetCaptcha}
            >
              {count
                ? `${count} s`
                : "发送验证码"}
            </Button>
          </Col>
        </Row>
        <FormItem>
          <Button
            loading={registing}
            className={styles.submit}
            type="primary"
            htmlType="submit"
          >
            注册
          </Button>
          <Link className={styles.login} to="/user/login">
            登录
          </Link>
        </FormItem>
      </Form>
    )

  return (
    <div className={styles.main}>
      <Tabs defaultActiveKey={registerType} onChange={(type) => setRegisterType(type)}>
        {/* <TabPane tab="手机号注册" key="phone">
          {renderRegisterContent}
        </TabPane> */}
        <TabPane tab="邮箱注册" key="email">
          {renderRegisterContent}
        </TabPane>
      </Tabs>
    </div>
  );
};

export default connect(({ user }) => ({
  user,
}))(Register);
